<template>
    <div>
        <!-- 内容 -->
        <el-card shadow="never" class="border-0">
            <!-- 选项卡 -->
            <!-- <el-tabs v-model="searchForm.types" @tab-change="getList" class="mb-2">
                <el-tab-pane :label="item.name" :name="item.key" v-for="(item, index) in tabbars"
                    :key="index"></el-tab-pane>
            </el-tabs> -->
            <!-- 搜索 -->
            <SearchForm :model="searchForm" @search="getList" @reset="resetSearchForm">
                <SearchItem label="">

                    <div class="mt-4" style="width: 100%;margin-left: 0px !important;">

                        <el-input v-model="searchForm.title" placeholder="媒体名称" class="input-with-select">
                            <template #prepend>
                                <el-button :icon="Search" />
                            </template>
                            <template #append>
                                <el-select v-model="searchForm.types" placeholder="请选择状态" style="width: 130px">
                                    <el-option v-for="(item, index) in tabbars" :key="item.key" :label="item.name"
                                        :value="item.key" />
                                </el-select>
                            </template>
                        </el-input>
                    </div>
                    <!-- <div class="mt-4" style="width: 100%;margin-left: 0px !important;">

                        <el-input v-model="searchForm.title" placeholder="媒体名称" class="input-with-select">
                            <template #prepend>
                                <el-button :icon="Search" />
                            </template>
                            <template #append>
                                <el-select v-model="searchForm.types" placeholder="请选择状态" style="width: 130px">
                                    <el-option v-for="(item, index) in tabbars" :key="item.key" :label="item.name"
                                        :value="item.key" />
                                </el-select>
                            </template>
                        </el-input>
                    </div> -->


                </SearchItem>
            </SearchForm>
            <!-- 新增|刷新 -->
            <ListHeader layout="create,refresh" @create="selfhandleCreate" @refresh="getList"
                @delete="handleMultiDelete">
                <!-- <el-popconfirm
                  v-if="searchForm.types != ''"
                  title="是否要继续操作选中记录？"
                  confirmButtonText="确认"
                  cancelButtonText="取消"
                  @confirm="handleMultiData(null,{agree: true})"
                >
                  <template #reference>
                    <el-button type="warning" size="small">
                      <el-icon class="el-icon--left" :size="16">
                        <Finished />
                      </el-icon>
                      <span v-if="searchForm.types == 'delete'">批量恢复</span>
                      <span v-if="searchForm.types == 'pass'">批量分发</span>
                      <span v-else-if="searchForm. types == 'distribute'">撤回分发</span>
                      <span v-else>批量提交</span>
                    </el-button>
                  </template>
                </el-popconfirm> -->
            </ListHeader>

            <!-- 表格 -->
            <el-table ref="multipleTableRef" @selection-change="handleSelectionChange" :data="tableData" stripe
                style="width: 100%" v-loading="loading">
                <el-table-column type="selection" width="55" />
                ·
                <el-table-column label="封面" width="300">
                    <template #default="{ row }">
                        <div class="flex">
                            <el-image class="mr-3 rounded" :src="row.cover_image_url" fit="cover" :lazy="true"
                                style="width: 50px; height: 50px"></el-image>
                            <div class="flex-1">
                                <p>{{ row.title }}</p>
                                <p class="text-gray-400 text-xs">创建时间：{{ row.add_time }} </p>
                                <!--                                <p class="text-gray-400 text-xs mb-1">套餐:{{ row.label }}</p>-->
                                <!--                                <p class="text-gray-400 text-xs mb-1">详情:{{ row.desc }}</p>-->
                            </div>
                        </div>
                    </template>
                </el-table-column>


                <!-- <el-table-column label="内容标签" width="200">
                    <template #default="{ row }">
                        <div class="flex" v-for="(item, index) in row.labels">
                            <div class="flex-1">
                                <p>{{ item.label }}</p>
                            </div>
                        </div>
                    </template>
                </el-table-column> -->

                <el-table-column label="发布平台" width="300">
                    <template #default="{ row }">
                        <div class="flex" v-for="(item, index) in row.platefroms">
                            <el-image class="mr-3 rounded" :src="item.icon" fit="cover" :lazy="true"
                                style="width: 30px; height: 30px"></el-image>
                            <div class="flex-1">
                                <p>{{ item.name }}</p>
                            </div>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="状态" width="150" align="center">
                    <template #default="{ row }">
                        <!-- 个人发布 -->
                        <div class="flex flex-col">
                            <!-- <el-button @click="openShipInfoModal(row.media_logs)"
                                :type="row.types == 'delete' || row.types == 'no_pass' ? 'danger' : 'success'"
                                size="small" plain>{{getTabbars(row.types).name}}
                            </el-button> -->
                            <el-button :type="row.types == 'delete' || row.types == 'no_pass' ? 'danger' : 'success'"
                                size="small" plain>{{ getTabbars(row.types).name }}
                            </el-button>
                        </div>
                    </template>
                </el-table-column>

                <!--        <el-table-column label="媒体日志" align="center">-->
                <!--          <template #default="{ row }" class="flex flex-col">-->
                <!--            <el-button type="primary" text @click="openShipInfoModal(row.media_logs)"-->
                <!--              :loading="shipLoading">查看进度</el-button>-->
                <!--          </template>-->
                <!--        </el-table-column>-->

                <el-table-column flex label="操作" align="center">
                    <template #default="scope">
                        <div>
                            <el-button class="px-1" type="primary" size="small" text
                                v-if="scope.row.types == 'saves' || scope.row.types == 'no_pass'"
                                @click="selfHandleEdit(scope.row)">
                                <el-icon class="el-icon--left" :size="16">
                                    <Setting />
                                </el-icon>
                                修改信息
                            </el-button>
                            <!-- 
                            <el-popconfirm title="是否要上传提交该媒体？" confirmButtonText="确认" cancelButtonText="取消"
                                v-if="scope.row.types == 'saves' || scope.row.types == 'no_pass'"
                                @confirm="handleMultiData(scope.row.id, { agree: '1' })">
                                <template #reference>
                                    <el-button class="px-1" text type="success"
                                        v-permission="['MediaContent,partial_update']">
                                        <el-icon class="el-icon--left" :size="16">
                                            <Top />
                                        </el-icon>
                                        提交
                                    </el-button>
                                </template>
        </el-popconfirm> -->

                            <!-- <el-popconfirm title="是否要发布该媒体？" confirmButtonText="确认"
                                           cancelButtonText="取消"
                                           v-if="scope.row.types == 'pass'"
                                           @confirm="handleMultiData(scope.row.id,{agree:'1'})">
                                <template #reference>
                                    <el-button class="px-1" text type="success"
                                               v-permission="['MediaContent,partial_update']">
                                        <el-icon class="el-icon--left" :size="16">
                                            <Top/>
                                        </el-icon>
                                        发布
                                    </el-button>
                                </template>
                            </el-popconfirm> -->

                            <el-popconfirm title="是否要删除该媒体？" confirmButtonText="确认" cancelButtonText="取消"
                                v-if="scope.row.types == 'saves' || scope.row.types == 'no_pass'"
                                @confirm="handleDelete([scope.row.id])">
                                <template #reference>
                                    <el-button class="px-1" text type="danger"
                                        v-permission="['MediaContent,bulk_deletes']">
                                        <el-icon class="el-icon--left" :size="16">
                                            <Delete />
                                        </el-icon>
                                        删除
                                    </el-button>
                                </template>
                            </el-popconfirm>

                            <div v-permission="['hasAuth']" class="flex flex-col justify-center items-center"
                                v-if="scope.row.types != 'saves' && scope.row.types != 'no_pass'">
                                <el-button type="success" class="w-30" size="small" plain
                                    @click="handleRefund(scope.row.id, true)" v-if="scope.row.types == 'checking'">审核通过
                                </el-button>
                                <el-button class="mt-2 !ml-0 w-30" type="danger" size="small" plain
                                    @click="handleRefund(scope.row.id, false)" v-if="scope.row.types == 'checking'">审核驳回
                                </el-button>
                                <el-button class="mt-2 !ml-0 w-30" type="warning" size="small" plain
                                    @click="handleRefund(scope.row.id, false)" v-if="scope.row.types == 'pass'">审核撤回
                                </el-button>

                            </div>
                        </div>

                    </template>
                </el-table-column>
            </el-table>

            <div class="flex items-center justify-center mt-5">
                <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                    :page-size="pageSize" @current-change="getList" />
            </div>

            <FormDrawer destroyOnClose ref="formDrawerRef" :title="drawerTitle" @submit="selfHandleSubmit" size="30%">
                <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
                    <block v-if="has_skus">
                        <el-form-item label="可用次数">
                            <el-input v-model="balance_times" aria-readonly="true" class="input-width"></el-input>
                        </el-form-item>

                        <el-form-item label="选择账户" prop="platefrom">
                            <el-select v-model="form.accounts" @change="setTotal" filterable clearable multiple
                                class="input-width" placeholder="选择账户">
                                <el-option v-for="item in accountsList" :key="item.id" :label="item.plate_account"
                                    :value="item.plate_account" />
                            </el-select>
                        </el-form-item>

                    </block>

                    <block v-else>
                        <!-- <el-form-item label="选择平台" prop="platefrom">
                            <el-select v-model="form.platefroms" @change="setTotal" filterable clearable multiple
                                class="input-width" placeholder="选择平台">
                                <el-option v-for="item in platfromList" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item> -->

                        <el-form-item label="选择账户" prop="platefrom">
                            <el-select v-model="form.accounts" @change="setTotal" filterable clearable multiple
                                class="input-width" placeholder="选择账户">
                                <el-option v-for="item in accountsList" :key="item.id"
                                    :label="`${item.plate_account} -- ${item.en_name}`" :value="item.id" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="单条价格" prop="item_price">
                            <el-input disabled v-model="item_price" placeholder="单条价格" class="input-width"></el-input>
                        </el-form-item>

                        <el-form-item label="总价格" prop="price">
                            <el-input v-model="form.price" placeholder="总价格" class="input-width"></el-input>
                        </el-form-item>
                    </block>
                    <!-- 
                    <el-form-item label="标签" prop="label">

                        <el-select v-model="form.labels" filterable clearable multiple class="input-width"
                            placeholder="标签">
                            <el-option v-for="item in label_list" :key="item.id" :label="item.label" :value="item.id" />
                        </el-select>

                    </el-form-item> -->

                    <el-form-item label="媒体类型" prop="content_type">
                        <el-radio-group v-model="form.content_type">
                            <el-radio v-for="item in content_type_list" :key="item.value" :label="item.value"
                                size="large" border>{{
                item.label }}</el-radio>
                        </el-radio-group>
                    </el-form-item>


                    <el-form-item label="分类" prop="label_type">
                        <span v-for="tag in label_list">
                            <el-check-tag style="margin-left: 3px;" type="primary" :checked="tag.checked"
                                @change="onChange(tag.id)" :key="tag.id" :disable-transitions="false"
                                @close="handleClose(tag.id)">
                                {{ tag.label }}
                            </el-check-tag>
                        </span>
                        <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="normal"
                            @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                        <el-button v-else class="button-new-tag" style="margin-left: 3px;" size="small" @click="showInput">
                            + 自定义
                        </el-button>
                    </el-form-item>

                    <el-form-item label="封面" prop="covers">
                        <ChooseImage :limit="4" v-model="form.covers" @getImageId="getCoversId" />
                    </el-form-item>

                    <el-form-item label="标题" prop="title">
                        <el-input v-model="form.title" placeholder="媒体标题" class="input-width"></el-input>
                    </el-form-item>

                    <el-form-item label="简介" prop="desc">
                        <el-input type="textarea" v-model="form.desc" placeholder="媒体简介" class="input-width"></el-input>
                    </el-form-item>

                    <!-- <el-form-item label="排序" prop="order">
                        <el-input-number v-model="form.order" :min="0" :max="1000" class="input-width" />
                    </el-form-item> -->



                    <el-form-item v-if="form.content_type == '1'" label="文章内容" prop="content" class="mr-5">
                        <Editor v-model="form.content" />
                    </el-form-item>

                    <el-form-item v-if="form.content_type == '3'" label="媒体图片" prop="media_images" class="mr-5">
                        <ChooseImage :limit="9" v-model="form.media_images" @getImageId="getImageId" />
                    </el-form-item>

                    <el-form-item v-if="form.content_type == '2'" label="媒体视频" prop="media_videos">
                        <video :src="form.media_videos_url" v-if="form.media_videos_url" controls  class="w-[100px] h-[100px] rounded border mr-2"></video>
                        <ChooseVideo :limit="1" v-model="form.media_videos" @getImageId="getVideoId" @getImageUrl="getImageUrl" />
                    </el-form-item>
                </el-form>
            </FormDrawer>
        </el-card>
        <!-- <content ref="contentRef" @reload-data="getList" /> -->
        <ShipInfoModal ref="ShipInfoModalRef" />


        <el-dialog v-model="dialogVisible" title="提示" width="70%" :before-close="handleClose">
            <span>检测到您绑定的账户中含有未登录过app的账户，请在左侧操作栏【用户管理->账户平台】的数据列表中进行登录app，拉取app操作</span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="login_and_get_acount">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, onMounted, nextTick } from 'vue'
import ListHeader from '~/components/ListHeader.vue'
import FormDrawer from '~/components/FormDrawer.vue'
import ChooseImage from '~/components/ChooseImage.vue'
import ChooseVideo from '~/components/ChooseVideo.vue'
import SearchForm from "~/components/SearchForm.vue"
import SearchItem from "~/components/SearchItem.vue"
import { Search } from '@element-plus/icons-vue'
// import Content from './content.vue'
import Editor from '~/components/Editor.vue'
import ShipInfoModal from './ShipInfoModal.vue'
import { showModal, showPrompt } from '~/composables/util'
import { useRouter } from 'vue-router'
// api
import {
    getMediasList,
    postMedias,
    putMedias,
    patchMediasData,
    deleteMedias,
    patchMediasSubmit,
} from '~/api/medias/index'
import {
    getALLContentLabelList, postContentLabel
} from '~/api/medias/content_label'
import { getPlatefromAll, getPlatefromByUser } from '~/api/platefrom/index'
import { getAppLoginFile } from '~/api/user/index'


import { useInitTable, useInitForm } from '~/composables/useCommon'
import { useStore } from 'vuex'
import { getSkusByAccountID } from "~/api/platefrom/skus"
import { forEach, fromPairs } from 'lodash'
const store = useStore()
const empty = new URL(`/src/assets/empty.png`, import.meta.url).href
const router = useRouter()

// 公共方法
import { getContentType } from '~/composables/util'


// 媒体套餐
const has_skus = ref(false)
const sku_list = ref([])
const balance_times = ref('0')
const content_type_list = ref([])
const label_list = ref([])
const platfromList = ref([])
const item_price = ref('')
const InputRef = ref(null)
const inputValue = ref('')
const inputVisible = ref(false)
const handleClose = () => {
    label_list.value.splice(label_list.value.indexOf(tag), 1)
}

const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        InputRef.value.focus()
    })
}

const handleInputConfirm = () => {
    if (inputValue.value) {
        postContentLabel({ label: inputValue.value }).then((res) => {
            res.checked = true
            label_list.value.push(res)
        })

    }
    inputVisible.value = false
    inputValue.value = ''
}

const onChange = (id) => {
    label_list.value.forEach((item) => {
        if (item.id == id) {
            item.checked = !item.checked
        }
    })
}

onMounted(() => {
    // 加载套餐数据 -- 获取本人的套餐数据
    getSkusByAccountID({
        id: store.state.user.id,
        group_id: store.state.user.group,
        company_id: store.state.user.company_id,
    }).then((res) => {
        content_type_list.value = getContentType(res.data.skus[0].content_type_ids)
        if (res.data.skus[0].id != 1) {
            has_skus.value = true
            let arr = []
            arr.push(res.data.skus[0])
            sku_list.value = arr
            balance_times.value = res.data.list[0].balance_times
            form.sku = res.data.skus[0].id
        } else {
            has_skus.value = false
            form.sku = '1'
            item_price.value = res.data.skus[0].item_price
        }
    })

    // 加载label
    getALLContentLabelList().then((res) => {
        label_list.value = res.data
        label_list.value.forEach((item) => {
            item.checked = false
        })
    })
    // 获取平台信息
    getPlatefromByUser({}).then((res) => {
        platfromList.value = res.data
    })
})


const {
    searchForm,
    resetSearchForm,
    tableData,
    loading,
    currentPage,
    total,
    pageSize,
    getList,
    hanledStatus,
    handleDelete,
    multipleTableRef,
    handleSelectionChange,
    handleMultiDelete,
    handleMultiData,
    handleMultiTypes,
    handlePatchMultiSubmit,
} = useInitTable({
    searchForm: { search: '', types: '', sku: null },
    requestListAPI: getMediasList,
    upMultiData: patchMediasData,
    upMultiSubmit: patchMediasData,
    delete: deleteMedias,
    // pageSize: store.state.pageSize.MediasList,
    pageSize: 10,
    onGetListSuccess: res => {
        tableData.value = res.data.results
        total.value = res.count
    },
    onUpdateStatusSuccess: (row, status) => {
        // row.status = status
    },
})
const {
    formDrawerRef,
    formRef,
    form,
    rules,
    editId,
    drawerTitle,
    handleSubmit,
    resetForm,
    handleCreate,
    handleEdit,
} = useInitForm({
    getList,
    update: putMedias,
    create: postMedias,
    form:
    {
        title: "",
        labels: '',
        label: '',
        accounts: [],
        content: "",
        add_time: null,
        desc: "",
        sku: '',
        cover_image_id: '',
        content_type: '2',
        disagree_reason: "",
        order: 50,
        types: 'saves',
        covers: "",
        media_images: '',
        media_videos: '',
        covers_ids: [],
        media_images_ids: [],
        media_videos_ids: [],
        platefroms: [],
        item_price: '',
        price: '',
        media_videos_url:'',
    },
    rules: {
        title: [
            {
                required: true,
                message: '标题不能为空',
                trigger: 'blur',
            },
        ],
        sku: [
            {
                required: true,
                message: '套餐不能为空',
                trigger: 'blur',
            },
        ],
        covers: [
            {
                required: true,
                message: '封面不能为空',
                trigger: 'blur',
            },
        ],
    },
})
// 获取图片id
// const getImageId = ids => {
//     form.covers_ids = ids
// }

const selfHandleSubmit = () => {
    if (form.labels.length > 0) {
        form.label = form.labels.join(',')
    }
    if (form.covers_ids.length > 0) {
        form.cover_image_id = form.covers_ids.join(',')
    }
    
    let labels = label_list.value.filter(item => item.checked).map(item => item.id);
    if (labels.length > 0) {
        form.label = labels.join(',')
    } else {
        form.label = ''
    }

    // 图片
    if (form.content_type == 1) {
        form.media = form.media_images
    }
    // 视频
    if (form.content_type == 2) {
        form.media = form.media_videos
    }
    form.skus_id = store.state.user.skus_id

    // 设置form.plateform_id
    let platefrom_ids = form.accounts.map(index => accountsList.value.find((item) => item.id == index).platefrom_id)
    let uniquePlatefrom_ids = Array.from(new Set(platefrom_ids));
    form.platefroms = uniquePlatefrom_ids
    handleSubmit()
}

// 选项卡
const tabbars = [
    {
        key: '',
        name: '全部',
    },
    {
        key: 'saves',
        name: '保存',
    },
    {
        key: 'checking',
        name: '审核中',
    },
    {
        key: 'no_pass',
        name: '未通过',
    },
    {
        key: 'pass',
        name: '已通过',
    },
    {
        key: 'distribute',
        name: '分发中',
    },
    {
        key: 'pass_distribute',
        name: '已分发',
    },
    {
        key: 'delete',
        name: '回收站',
    },
]

const getTabbars = (types) => {
    return tabbars.find(item => item.key == types)
}

// 展开收起
const showSearch = ref(false)

// 设置媒体详情
// const contentRef = ref(null)
// const handleSetMediasContent = row => contentRef.value.open(row)

// 审核进度
const shipLoading = ref(false)
const ShipInfoModalRef = ref(null)
const openShipInfoModal = id => {
    shipLoading.value = true
    ShipInfoModalRef.value.open(id)
    shipLoading.value = false
}

// 审核通过或拒绝
const handleRefund = (id, agree) => {
    ; (agree
        ? showModal('是否同意该媒体审核通过？')
        : showPrompt('请输入驳回理由', 200)
    ).then(({ value }) => {
        let data = { agree }
        if (!agree) {
            data.disagree_reason = value
        }
        handleMultiData(id, data)
    })
}

// 获取图片id
const getCoversId = ids => {
    form.covers_ids = ids
}
const getImageId = ids => {
    form.media_images_ids = ids
}
const getVideoId = ids => {
    form.media_videos_ids.push(ids)
}
const getImageUrl = url => {
    form.media_videos_url = url
}


// 设置总价格
const setTotal = () => {
    form.price = form.accounts.length * item_price.value
    form.sku = 1
}

// 查看是否有未绑定的账户
const dialogVisible = ref(false)
const accountsList = ref([])
const selfhandleCreate = () => {
    getAppLoginFile().then((res) => {
        if (res.data.length < 1) {
            dialogVisible.value = true
        } else {
            accountsList.value = res.data
            handleCreate()
        }
    })
}

const selfHandleEdit = (row) => {
    getAppLoginFile().then((res) => {
        if (res.data.length < 1) {
        } else {
            accountsList.value = res.data
        }
    })
    handleEdit(row)
}

// 跳转列表
const login_and_get_acount = () => {
    dialogVisible.value = false
    router.push({ path: "/user/platefrom" })
}
</script>
